package cn.redragon.soa.service.impl;

import brave.Tracer;
import cn.redragon.soa.data.dao.SystemLogDao;
import cn.redragon.soa.data.entity.SystemLogEntity;
import cn.redragon.soa.model.dto.SystemLogDTO;
import cn.redragon.soa.model.mapper.SystemLogMapper;
import cn.redragon.soa.service.SystemLogService;
import io.vavr.control.Try;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@ConditionalOnClass(JpaRepository.class)
public class SystemLogServiceImpl implements SystemLogService {

    private final SystemLogDao systemLogDao;
    
    private final Tracer tracer;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(final SystemLogDTO dto) {
        String traceId = Try.of(() -> tracer.currentSpan().context().traceIdString()).getOrElse(() -> null);
        SystemLogEntity systemLogEntity = SystemLogMapper.INSTANCE.mapper(dto);
        systemLogEntity.setTraceId(traceId);
        systemLogDao.save(systemLogEntity);
    }
}
